<template>
  <div class="box">
    <div class="box-left" :style="`width: ${leftOpen ? '180' : '5'}px`">
      <template v-if="leftOpen">
        <div class="left-item" :class="active == idx ? 'active' : ''" v-for="(item, idx) in leftList" :key="idx"
          @click="leftClick(idx)">{{ item }}</div>
      </template>
      <div class="icon" @click="leftOpen = !leftOpen;"><i :class="`el-icon-arrow-${leftOpen ? 'left' : 'right'}`"></i>
      </div>
    </div>
    <div class="box-right" ref="targetElement" :style="`width: calc(100% - ${leftOpen ? '195' : '20'}px)`">
      <div class="search-box" ref="searchBox">
        <div class="search-top-box">
          <div class="search-top-left-box">
            <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
              class="demo-form-inline">
              <el-form-item :label="leftList[active]">
                <el-input @change="onSearch" clearable class="form-width" v-model="formSearch.keyword"
                  :placeholder="`输入${leftList[active]}`"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="search-top-right-box">
            <!-- <p @click="moreSearchFunc">
              {{ moreSearchShow ? "收起" : "展开"
              }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                "></i>
            </p> -->
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="primary" @click="dialogFormVisible = true; formType = 'add'" v-if="isPerAddFunc">新增{{
              leftList[active]
            }}</el-button>
          </div>
        </div>
      </div>
      <!-- table -->
      <div class="page-list" ref="pageList">
        <div class="list-top-box">
          <p class="list-top-box-left">
            已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
          </p>
          <div class="list-top-box-right">
            <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
              v-if="isPerEditFunc">编辑</el-button>
            <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
              v-if="isPerDelFunc">删除</el-button>
          </div>
        </div>
        <div class="table-box" v-loading="tableLoading">
          <el-table ref="table" :header-cell-style="{
            background: '#FAFBFC',
            color: '#828A9D',
            textAlign: 'center',
          }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
            @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable" height="100%">
            <el-table-column type="selection" width="80"></el-table-column>
            <el-table-column min-width="180px" prop="name" :label="leftList[active]"
              show-overflow-tooltip></el-table-column>
            <el-table-column min-width="180px" prop="handlers_name" label="创建人" show-overflow-tooltip></el-table-column>
            <el-table-column min-width="180px" prop="created_at" label="创建时间" show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
        <div class="page-footer">
          <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page"
            :page-size="num" @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog destroy-on-close :title="formType == 'add' ? `添加${leftList[active]}` : `修改${leftList[active]}`"
      :visible.sync="dialogFormVisible" :modal-append-to-body="false" @close="visibleClose"
      :close-on-click-modal="false" width="460px">
      <el-form :model="formData" :rules="formRules" class="user-info" ref="dialogFrom" label-width="110px"
        label-position="left">
        <el-form-item :label="leftList[active]" prop="name">
          <el-input v-model="formData.name" :placeholder="`请输入${leftList[active]}`"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="visibleClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import configApi from '@/api/configApi'

export default {
  name: "configurations",
  data() {
    return {
      // 侧边栏
      leftOpen: true,
      active: 0,
      leftList: ['施工阶段', '超期类型', '售后责任判定', '售后类型划分', '增减内容'],

      tableLoading: false,//列表loading
      tableData: [],//列表数据
      formSearch: { keyword: '' },//搜索form
      moreSearchShow: false,//
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选数据

      // 弹窗
      formType: 'add',
      dialogFormVisible: false,
      submitBtn: false,
      formData: {
        id: '',
        name: '',
      },
      formRules: {
        name: [{ required: true, message: `请输入`, trigger: "change" }],
      },
      permission: [],//操作权限

    };
  },
  watch: {},
  computed: {
    // 判断删除按钮是否存在
    isPerDelFunc() {
      let leftList = this.leftList;
      let active = this.active;
      switch (leftList[active]) {
        case '施工阶段':
          return this.$isPer(this.permission, ['constructionStage_del'])
          break;
        case '超期类型':
          return this.$isPer(this.permission, ['overdueType_del'])
          break;
        case '售后责任判定':
          return this.$isPer(this.permission, ['responsibleParty_del'])
          break;
        case '售后类型划分':
          return this.$isPer(this.permission, ['problemType_del'])
          break;
        case '增减内容':
          return this.$isPer(this.permission, ['changeContent_del'])
          break;
        default:
      }
    },
    // 判断编辑按钮是否存在
    isPerEditFunc() {
      let leftList = this.leftList;
      let active = this.active;
      switch (leftList[active]) {
        case '施工阶段':
          return this.$isPer(this.permission, ['constructionStage_edit'])
          break;
        case '超期类型':
          return this.$isPer(this.permission, ['overdueType_edit'])
          break;
        case '售后责任判定':
          return this.$isPer(this.permission, ['responsibleParty_edit'])
          break;
        case '售后类型划分':
          return this.$isPer(this.permission, ['problemType_edit'])
          break;
        case '增减内容':
          return this.$isPer(this.permission, ['changeContent_edit'])
          break;
        default:
      }
    },
    // 判断新增按钮是否存在
    isPerAddFunc() {
      let leftList = this.leftList;
      let active = this.active;
      switch (leftList[active]) {
        case '施工阶段':
          return this.$isPer(this.permission, ['constructionStage_add'])
          break;
        case '超期类型':
          return this.$isPer(this.permission, ['overdueType_add'])
          break;
        case '售后责任判定':
          return this.$isPer(this.permission, ['responsibleParty_add'])
          break;
        case '售后类型划分':
          return this.$isPer(this.permission, ['problemType_add'])
          break;
        case '增减内容':
          return this.$isPer(this.permission, ['changeContent_add'])
          break;
        default:
      }
    },

  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })

    this.getList();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    leftClick(idx) {
      if (idx == this.active) return
      this.active = idx
      this.formSearch.keyword = ""
      this.tableData = []
      this.multipleSelection = []
      this.onSearch(1)
    },

    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    editFunc() {
      let item = this.multipleSelection[0];
      console.log(item)
      this.formType = 'update'
      this.formData.id = item.id
      this.formData.name = item.name
      this.dialogFormVisible = true
    },
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.name)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(id_arr)
        configApi.setDel({ id_arr }, this.active).then((res) => {
          console.log(res, "删除");
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });

    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },

    // 弹窗
    visibleClose() {
      this.formData.name = ''
      this.dialogFormVisible = false;
    },
    saveSubmit() {
      this.$refs['dialogFrom'].validate((valid) => {
        if (valid) {
          this.submitBtn = true
          let formData = this.formData;
          if (this.formType == 'add') {
            configApi.setAdd({
              name: formData.name,
            }, this.active).then(res => {
              console.log(res, '新增')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch(1)
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          } else {
            configApi.setUpdate({
              id: formData.id,
              name: formData.name,
            }, this.active).then(res => {
              console.log(res, '更新')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch()
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          }
        } else {
          return false;
        }
      });
    },

    // 获取列表数据
    getList() {
      this.tableLoading = true
      configApi.getList({
        page: this.page,
        num: this.num,
        name: this.formSearch.keyword,
      }, this.active).then((res) => {
        console.log(res, "获取列表");
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: "warning",
        });
      });
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>